package com.niguang.work.labour.common.util;

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;


/**
 * xml util
 */
public class XmlUtils {


    /**
     * 字符出格式化为xml
     *
     * @param inputXML
     * @return
     * @throws Exception
     */
    public static String formatXML(String inputXML) {
        SAXReader reader = new SAXReader();
        String requestXML = null;
        try {
            Document document = reader.read(new StringReader(inputXML));
            XMLWriter writer = null;
            if (document != null) {
                try {
                    StringWriter stringWriter = new StringWriter();
                    OutputFormat format = new OutputFormat(" ", true);
                    writer = new XMLWriter(stringWriter, format);
                    writer.write(document);
                    writer.flush();
                    requestXML = stringWriter.getBuffer().toString();
                } finally {
                    if (writer != null) {
                        try {
                            writer.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
            System.out.println(requestXML);
            return requestXML;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return requestXML;
    }

    /**
     * 将XML转为指定的POJO
     *
     * @param clazz
     * @param xmlStr
     * @return
     * @throws Exception
     */
    public static <T> T xmlToBean(Class<T> clazz, String xmlStr) {
        Object xmlObject = null;
        Reader reader = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            // XML 转为对象的接口
            Unmarshaller unmarshaller = context.createUnmarshaller();
            reader = new StringReader(xmlStr);
            //以文件流的方式传入这个string
            xmlObject = unmarshaller.unmarshal(reader);
            if (null != reader) {
                reader.close();
            }
            return (T) xmlObject;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

}
